package dateManager;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import loginRegister.LoginBean;
import Bean.CheckBean;
import Bean.SqlBean;

/**
 *
 * @author 刘杉
 */
public class AddDateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws  IOException {
        String date=new String(request.getParameter("date").getBytes("ISO-8859-1"),"UTF-8");
        String thing=new String(request.getParameter("thing").getBytes("ISO-8859-1"),"UTF-8");
        String userName="";
        HttpSession session=request.getSession();
        LoginBean login=(LoginBean)session.getAttribute("login");
        if(login==null){
            response.sendRedirect("http://localhost:8080/login.jsp");
        }else{
            userName=login.getUserName();
            try{
                ResultSet rs = null;
                SqlBean sb = new SqlBean();
                sb.connectSQL();
                String sql1="select * from date where date='"+date+"'and userName='"+userName+"'";
                rs=sb.executeQuery(sql1);
                if(rs.next()){
                    CheckBean.alert("该日程已有计划，添加失败！");
                    response.sendRedirect("http://localhost:8080/dateManager/addDate.jsp");
                }else{
                    String sql2="insert into date"+"(userName,date,thing)"+"values("+"'"+userName+"'"+","+"'"+date+"'"+","+"'"+thing+"'"+")";
                    sb.executeUpdate(sql2);
                    String sql3="select * from date where userName='"+userName+"'";
                    rs=sb.executeQuery(sql3);
                    ArrayList datelist=null;
                    datelist=new ArrayList();
                    while(rs.next()){
                        LookDateBean dd=new LookDateBean();
                        dd.setDate(rs.getString("date"));
                        dd.setThing(rs.getString("thing"));
                        datelist.add(dd);
                    }
                    session.setAttribute("datelist", datelist);
                    sb.closeSQL();
                    CheckBean.alert("填写信息合格，添加成功！");
                    response.sendRedirect("http://localhost:8080/dateManager/addDate.jsp");
                }
                sb.closeSQL();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws  IOException {
        doGet(request, response);
    }

}